package com.hlt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlt.context.BaseContext;
import com.hlt.dto.FavoritesDTO;
import com.hlt.dto.FavoritesPageQueryDTO;
import com.hlt.entity.Favorites;
import com.hlt.entity.Posts;
import com.hlt.mapper.FavoritesMapper;
import com.hlt.mapper.PostsMapper;
import com.hlt.result.PageResult;
import com.hlt.service.IFavoritesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.config.UserStatsUtils;
import com.hlt.vo.FavoritesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2024-11-25
 */
@Service
public class FavoritesServiceImpl extends ServiceImpl<FavoritesMapper, Favorites> implements IFavoritesService {

    @Autowired
    private PostsMapper postsMapper;

    @Autowired
    private UserStatsUtils userStatsUtils;

    @Override
    @Transactional
    public void addFavorite(FavoritesDTO favoritesDTO) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 参数校验
        Assert.notNull(favoritesDTO.getPostId(), "文章ID不能为空");

        // 检查文章是否存在
        Posts post = postsMapper.selectById(favoritesDTO.getPostId());
        if (post == null) {
            throw new IllegalArgumentException("文章不存在");
        }

        // 检查是否已收藏
        LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorites::getUserId, Math.toIntExact(userId))
                .eq(Favorites::getPostId, favoritesDTO.getPostId());
        if (count(queryWrapper) > 0) {
            throw new IllegalArgumentException("已经收藏过该文章");
        }

        // 创建收藏记录
        Favorites favorite = new Favorites();
        favorite.setUserId(Math.toIntExact(userId));
        favorite.setPostId(favoritesDTO.getPostId());
        favorite.setCreatedAt(LocalDateTime.now());

        // 保存收藏记录
        save(favorite);

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(userId), "favoritedPostsCount", true);

        // 更新文章收藏数量
        post.setFavoritesCount(post.getFavoritesCount() + 1);
        postsMapper.updateById(post);
    }

    @Override
    @Transactional
    public void removeFavorite(Integer postId) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 查询收藏记录
        LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorites::getUserId, Math.toIntExact(userId))
                .eq(Favorites::getPostId, postId);
        Favorites favorite = getOne(queryWrapper);

        if (favorite == null) {
            throw new IllegalArgumentException("收藏记录不存在");
        }

        // 物理删除收藏记录
        removeById(favorite.getFavoriteId());

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(userId), "favoritedPostsCount", false);

        // 更新文章收藏数量
        Posts post = postsMapper.selectById(postId);
        if (post != null) {
            post.setFavoritesCount(post.getFavoritesCount() - 1);
            postsMapper.updateById(post);
        }
    }

    @Override
    public PageResult getUserFavorites(FavoritesPageQueryDTO pageQueryDTO) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 构建分页对象
        Page<Favorites> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Favorites> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorites::getUserId, Math.toIntExact(userId))
                .orderByDesc(Favorites::getCreatedAt);

        // 执行分页查询
        page = page(page, queryWrapper);

        // 获取所有文章ID
        List<Integer> postIds = page.getRecords().stream()
                .map(Favorites::getPostId)
                .distinct()
                .collect(Collectors.toList());

        // 查询文章信息
        List<Posts> postsList = postsMapper.selectList(
                new LambdaQueryWrapper<Posts>().in(Posts::getPostId, postIds));
        Map<Integer, Posts> postMap = postsList.stream()
                .collect(Collectors.toMap(Posts::getPostId, post -> post));

        // 转换为VO对象
        List<FavoritesVO> favoritesVOList = page.getRecords().stream().map(favorite -> {
            FavoritesVO vo = new FavoritesVO();
            BeanUtils.copyProperties(favorite, vo);

            // 设置文章信息
            Posts post = postMap.get(favorite.getPostId());
            if (post != null) {
                vo.setTitle(post.getTitle());
            }

            return vo;
        }).collect(Collectors.toList());

        return new PageResult(page.getTotal(), favoritesVOList);
    }
}
